package com.example.administrator.view;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.administrator.base.BaseActivity;
import com.example.administrator.bean.MsgContent;
import com.example.administrator.module.UrlDefine;
import com.example.administrator.testapk.R;
import com.example.administrator.utils.IntentUtil;
import com.example.administrator.utils.NetUtils;
import com.example.administrator.utils.SpUtils;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Response;

public class AtyMain extends BaseActivity implements View.OnClickListener,PopupWindow.OnDismissListener{
    @BindView(R.id.cv_btn_exit)
    CardView cv_btn_exit;
    @BindView(R.id.cv_btn_nmsg)
    CardView cv_btn_nmsg;
    @BindView(R.id.cv_btn_emsg)
    CardView cv_btn_emsg;
    @BindView(R.id.cv_btn_umsg)
    CardView cv_btn_umsg;

    @BindView(R.id.tv_user_phone)
    TextView tv_user_phone;
    @BindView(R.id.iv_add)
    ImageView iv_add;
    @BindView(R.id.titleBar_main)
    TitleBar titleBar_main;
    @BindView(R.id.iv_person_image)
    ImageView iv_person_image;

    private static final String TAG = "AtyMain";
    private boolean isSet = false;   //是否设置了查询密码
    private PopupWindow popupWindow;
    private int navigationHeight;
    private WindowManager windowManager;
    private Display display ;
    private CustomPopWindow emsgPop,umsgPop,memuPop;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_main;
    }

    @Override
    protected void init() {
        windowManager = this.getWindowManager();
        display = windowManager.getDefaultDisplay();

        int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        navigationHeight = getResources().getDimensionPixelSize(resourceId);

        String str = (String) SpUtils.get(AtyMain.this,"phone","");
        tv_user_phone.setText(str);

        NetUtils.getInstance().getDataAsynFromNet(UrlDefine.ACTION_URL_HAVESETSEPWD, new NetUtils.MyNetCall() {
            @Override
            public void success(Call call, Response response) throws IOException {
                final String resData = response.body().string();
                Log.e("resData",resData);
                parseHAVESETSEPWDJsonData(resData);
            }

            @Override
            public void failed(Call call, IOException e) {
                Log.e(TAG,e.getMessage());
            }
        });
    }

    private void parseHAVESETSEPWDJsonData(String resData) {
        try{
            JSONObject searchpwdObject = new JSONObject(resData);
            String msg  = searchpwdObject.getString("msg");
            JSONObject data = searchpwdObject.getJSONObject("data");
            isSet = data.getBoolean("isSet");
            Log.e("isSet",isSet+"");
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void initView() {
        titleBar_main.setTitle("我的安记录");
        titleBar_main.addAction(new TitleBar.Action() {
            @Override
            public String getText() {
                return "";
            }

            @Override
            public int getDrawable() {
                return R.mipmap.more;
            }

            @Override
            public void performAction(View view) {
                overlay(AtySetSearchPwd.class);
            }
        });

        cv_btn_exit.setOnClickListener(this);
        cv_btn_nmsg.setOnClickListener(this);
        cv_btn_emsg.setOnClickListener(this);
        cv_btn_umsg.setOnClickListener(this);
        //floatbtn_set.setOnClickListener(this);
        iv_add.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.cv_btn_exit:
                showBottomPop(v);
                break;
            case R.id.cv_btn_nmsg:
                overlay(AtyNormalMsg.class);
                break;
            case R.id.cv_btn_emsg:
                showEmsgDialog();
                break;
            case R.id.cv_btn_umsg:
                showUmsgDialog();
                break;
            case R.id.iv_add:
                overlay(AtyAddMsg.class);
                break;
            case R.id.tv_sureexit:
                SpUtils.clear(AtyMain.this);
                forward(AtyLogin.class);
                break;
            case R.id.tv_cancel:
                popupWindow.dismiss();
                break;
            default:break;
        }
    }

    private void showBottomPop(View v) {
        if (popupWindow != null && popupWindow.isShowing()) {
            return;
        }

        View view = LayoutInflater.from(this).inflate(R.layout.view_popupwindow, null);
        popupWindow = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setAnimationStyle(R.style.PopupWindow);
        popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
        popupWindow.setOnDismissListener(this);
        setOnPopupViewClick(view);
        setBackgroundAlpha(0.5f);
    }

    private void setOnPopupViewClick(View view) {
        TextView tv_sureExit, tv_cancel;
        tv_sureExit = (TextView) view.findViewById(R.id.tv_sureexit);
        tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
        tv_sureExit.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
    }

    private void showEmsgDialog() {
        if(isSet == false){
                    AlertDialog.Builder builder = new AlertDialog.Builder(AtyMain.this);
                    builder.setTitle(R.string.dialog_title)
                            .setMessage(R.string.dialog_message).setPositiveButton(R.string.dialog_pbtn,new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            overlay(AtySetSearchPwd.class);
                        }

                    });

                    builder.setNegativeButton(R.string.dialog_nbtn,new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                        }
                    });
                    builder.show();
                }else{
                   showEpop();
                }
    }

    private void showEpop() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_encryption,null);
        handleEpopLogic(contentView);

        emsgPop = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .setAnimationStyle(R.style.PopupWindow)
                .size(display.getWidth()*3/5,display.getHeight()*2/5)
                .setFocusable(true)
                .setOutsideTouchable(true)
                .create()
                .showAtLocation(iv_person_image,Gravity.CENTER,0,0);
    }

    private void handleEpopLogic(View contentView) {
        TextView tv_cancel,tv_verify;
        final EditText et_spwd;
        et_spwd = (EditText) contentView.findViewById(R.id.et_searchpwd);
        tv_cancel = (TextView)contentView.findViewById(R.id.tv_cancle);
        tv_verify = (TextView)contentView.findViewById(R.id.tv_OK);

        View.OnClickListener listener = new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.tv_cancle:
                        emsgPop.dissmiss();
                        break;
                    case R.id.tv_OK:
                        if(!TextUtils.isEmpty(et_spwd.getText().toString())){

                            Map<String,String> reqbody = new ConcurrentSkipListMap<>();
                            reqbody.put("searchPassword", et_spwd.getText().toString());

                            NetUtils.getInstance().postDataAsynToNet(UrlDefine.ACTION_URL_SEARCHENCRYPTION, reqbody, new NetUtils.MyNetCall() {
                                @Override
                                public void success(Call call, Response response) throws IOException {

                                    final String normalmsg = response.body().string();

                                    try {
                                        JSONObject obj = new JSONObject(normalmsg);
                                        final String ss = obj.getString("msg");

                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                toast(ss);
                                                if(ss.equals("OK")){
                                                    Bundle bundle = new Bundle();
                                                    bundle.putString("searchPassword",et_spwd.getText().toString());
                                                    overlay(AtyEncryptionMsg.class,bundle);
                                                }
                                            }
                                        });
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void failed(Call call, IOException e) {
                                    Log.e(TAG, e.getMessage());
                                }
                            });
                        }
                        break;
                }
            }
        };
        tv_cancel.setOnClickListener(listener);
        tv_verify.setOnClickListener(listener);
    }

    private void showUmsgDialog() {
        if(isSet == false){
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(AtyMain.this);
                    builder1.setTitle(R.string.dialog_title)
                            .setMessage(R.string.dialog_message).setPositiveButton(R.string.dialog_pbtn,new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            overlay(AtySetSearchPwd.class);
                        }

                    });

                    builder1.setNegativeButton(R.string.dialog_nbtn,new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                        }
                    });
                    builder1.show();
                }else{
                    showUPop();
                }
    }

    private void showUPop() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_ultra,null);
        umsgPop = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .setAnimationStyle(R.style.PopupWindow)
                .size(display.getWidth()*3/5,display.getHeight()*2/5)
                .setFocusable(true)
                .setOutsideTouchable(true)
                .create()
                .showAtLocation(iv_person_image,Gravity.CENTER,0,0);
        handleLogicUPop(contentView);
    }

    private void handleLogicUPop(View contentView) {
        TextView tv_Ucancel,tv_Uverify,tv_sendCode;
        final EditText et_spwd,et_code;
        et_spwd = (EditText) contentView.findViewById(R.id.et_uspwd);
        et_code = (EditText) contentView.findViewById(R.id.et_verifyCode);
        tv_Ucancel = (TextView)contentView.findViewById(R.id.tv_ucancle);
        tv_Uverify = (TextView)contentView.findViewById(R.id.tv_uOK);
        tv_sendCode = (TextView)contentView.findViewById(R.id.btn_sendVerifyCode);
        View.OnClickListener Ulistener = new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.tv_ucancle:
                        umsgPop.dissmiss();
                        break;
                    case R.id.btn_sendVerifyCode:
                        //获取验证码
                        toast("获取验证码");
                        break;
                    case R.id.tv_uOK:
                        if(!TextUtils.isEmpty(et_spwd.getText().toString()) && !TextUtils.isEmpty(et_code.getText().toString())){

                            Map<String,String> reqbody = new ConcurrentSkipListMap<>();
                            reqbody.put("searchPassword", et_spwd.getText().toString());
                            reqbody.put("verifyCode", et_code.getText().toString());

                            NetUtils.getInstance().postDataAsynToNet(UrlDefine.ACTION_URL_SEARCHULTRA, reqbody, new NetUtils.MyNetCall() {
                                @Override
                                public void success(Call call, Response response) throws IOException {
                                    String res = response.body().string();
                                    Gson gson = new Gson();
                                    final MsgContent msgContent = gson.fromJson(res,MsgContent.class);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if(msgContent.getStatus() == 200){
                                                Bundle bun = new Bundle();
                                                bun.putString("searchPassword",et_spwd.getText().toString());
                                                bun.putString("verifyCode",et_code.getText().toString());
                                                overlay(AtyUltraMsg.class,bun);
                                            }
                                        }
                                    });
                                }

                                @Override
                                public void failed(Call call, IOException e) {
                                    Log.e(TAG, e.getMessage());
                                }
                            });
                        }
                        break;
                }
            }
        };
        tv_Ucancel.setOnClickListener(Ulistener);
        tv_Uverify.setOnClickListener(Ulistener);
        tv_sendCode.setOnClickListener(Ulistener);
    }

    @Override
    public void onDismiss() {
        setBackgroundAlpha(1);
    }

    private void setBackgroundAlpha(float alpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = alpha;
        getWindow().setAttributes(lp);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        memuPop.dissmiss();
        emsgPop.dissmiss();
        umsgPop.dissmiss();
        finish();
    }
}
